<template>
    <div class="login-container">
        <div class="login-box">
            <div class="login-title">
                <h2>宠物商店后台管理系统</h2>
            </div>

            <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="login-form">
                <el-form-item prop="username">
                    <el-input v-model="loginForm.username" placeholder="用户名" prefix-icon="el-icon-user" />
                </el-form-item>

                <el-form-item prop="password">
                    <el-input v-model="loginForm.password" placeholder="密码" prefix-icon="el-icon-lock" show-password
                        type="password" />
                </el-form-item>

                <el-form-item>
                    <el-button :loading="loading" type="primary" class="login-button" @click="handleLogin">
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User as ElIconUser, Lock as ElIconLock } from '@element-plus/icons-vue'
import { login } from '../api/user'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
    username: 'admin',
    password: '123456'
})

const loginRules = {
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const handleLogin = () => {
    loginFormRef.value.validate(valid => {
        if (!valid) return

        loading.value = true
        login(loginForm)
            .then(res => {
                localStorage.setItem('token', res.data.token)
                ElMessage({
                    type: 'success',
                    message: '登录成功'
                })
                router.push('/')
            })
            .catch(error => {
                console.error('登录失败:', error)
            })
            .finally(() => {
                loading.value = false
            })
    })
}
</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f0f2f5;
    background-image: url('../assets/images/pet-bg.jpg');
    background-size: cover;
    background-position: center;
}

.login-box {
    width: 400px;
    padding: 30px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-title {
    text-align: center;
    margin-bottom: 30px;
}

.login-title h2 {
    font-weight: 500;
    color: #333;
}

.login-button {
    width: 100%;
}
</style>